<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

use App\Models\CrawlerUrl;
use App\Models\CrawlerArticle;
use App\Handlers\CrawlerArticleHandler;

use App\Models\CrawlerPictuer;

class CrawlerArticleJobs implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $crawlerUrl;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(CrawlerUrl $crawlerUrl)
    {
        $this->crawlerUrl = $crawlerUrl;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // 通过内容处理器，处理 URL
        $r = new CrawlerArticleHandler($this->crawlerUrl);
        // 得到详细数据
        $result = $r->getResult();
        // 更新网址状态为已抓取
        \DB::connection('crawler-mysql')->table('crawler_urls')->where('id', $this->crawlerUrl->id)->update(['crawler' => 1]);
        // 如果有数据
        if ($result) {
            // 插入文章
            $article = CrawlerArticle::create($result);
            // 包含图片
            if($result['images']) {
                foreach($result['images'] as $v){
                    CrawlerPictuer::firstOrCreate([
                        'origin' => $v,
                        'crawler_article_id' => $article->id,
                        'category_id' => $result['category_id'],
                        'tags' => $result['tags']
                    ]);
                }
            }
        }
    }
}
